﻿/**

 * Copyright (c) 2015-2016, FastDev 刘强 (fastdev@163.com) & Quincy.

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

using OF.DistributeService.Core.Common;
using OF.Notify.Client;
using OF.Notify.DataHost.Cluster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OF.Notify.Entity
{
    public class VisitHeadTailLink
    {
        internal LinkItem<TopicMessage> currentItem = null;
        public HeadTailLink<TopicMessage> Link;
        public int CollectionId;
        public int ClusterId;

        public VisitHeadTailLink()
        { }

        internal LinkItem<TopicMessage> GetNext(out bool isLinkFull)
        {
            isLinkFull = Link.IsFull;
            LinkItem<TopicMessage> nextItem = Link.GetNext(currentItem);
            if(nextItem != null)
            {
                currentItem = nextItem;
            }
            return nextItem;
        }

        public VisitLinkResult VisitAll(ConsumerTopicDataNode consumerTopicDataNode)
        {
            int collectionId = this.CollectionId;
            while (true)
            {
                if (consumerTopicDataNode.dataNode.isDisposed)
                {
                    return VisitLinkResult.UnFinish;
                }
                bool isLinkFull = false;
                LinkItem<TopicMessage> message = GetNext(out isLinkFull);
                if (message == null)
                {
                    if (isLinkFull)
                    {
                        return VisitLinkResult.Finished;
                    }
                    else
                    {
                        return VisitLinkResult.UnFinish;
                    }
                }
                else
                {
                    try
                    {
                        consumerTopicDataNode.consumer.OnMessage(true, message.Data);
                    }
                    catch (Exception ex)
                    {
                        Util.LogException("ConsumeCollections, DataCollection:" + collectionId, ex);                        
                    }
                }
            }
        }
    }

    public enum VisitLinkResult
    { 
        Finished,
        UnFinish
    }
}
